package org.sasha.roulette.dialog;

import org.sasha.roulette.data.Spin;

import com.vaadin.data.Item;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormFieldFactory;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;

@SuppressWarnings("serial")
public class SpinForm extends Form {

    public interface Callback {
        void save(final Spin spin);
        void cancel();
    }
    
    private Callback callback;
    
    private HorizontalLayout footer = new HorizontalLayout();
    
    private Button commitButton = new Button("ОК", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            commit();
        }
    });
    
    private Button cancelButton = new Button("Отмена", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            discard();
            callback.cancel();
        }
    });
    
    private class ValueCombo extends NativeSelect {
        public ValueCombo() {
            super();
            setCaption("Значение");
            setNullSelectionAllowed(false);
            setNewItemsAllowed(false);
            for (int val = 0; val < 37; ++val) {
                addItem(val);
            }
        }
    }
    
    private final FormFieldFactory spinFactory = new FormFieldFactory() {
        
        @Override
        public Field createField(Item item, Object propertyId, Component uiContext) {
            if ("timestamp".equals(propertyId)) {
                final DateField df = new DateField();
                df.setCaption("Время/Дата");
                df.setDateFormat("dd-MM-yyyy hh:mm");
                return df;
            } else if ("value".equals(propertyId)) {
                return new ValueCombo();
            }
            return null;
        }
    };
    
    @Override
    @SuppressWarnings("unchecked")
    public BeanItem<Spin> getItemDataSource() {
        return (BeanItem<Spin>)super.getItemDataSource();
    };
    
    @Override
    public void commit() throws SourceException ,InvalidValueException {
        super.commit();
        callback.save(getItemDataSource().getBean());
    };
    
    public SpinForm(final Callback callback) {
        super();
        this.callback = callback;
        setFormFieldFactory(spinFactory);
        setFooter(footer);
        footer.setSpacing(true);
        footer.addComponent(commitButton);
        footer.addComponent(cancelButton);
        footer.setComponentAlignment(commitButton, Alignment.MIDDLE_RIGHT);
        footer.setComponentAlignment(cancelButton, Alignment.MIDDLE_LEFT);
        footer.setWidth("100%");
    }
}
